<!DOCTYPE html>
<html lang="zh-cn" dir="i18n">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- SEO -->
    <meta name="keywords" content="">
    <meta name="description" content="">

    <!-- Robots -->
    <meta name="robots" content="index,follow">
    <meta name="googlebot" content="index,follow">

    <!-- Render -->
    <meta name="renderer" content="webkit">
    <meta name="format-detection" content="telephone=no">
    <meta name="theme-color" content="#ffffff">
    <meta name="generator" content="codekit" />

    <!-- Control -->
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="x-dns-prefetch-control" content="off">

    <!-- Favicon -->
    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="bookmark" href="../favicon.ico" type="image/x-icon">

    <!-- Third Party -->
    <link crossorigin="anonymous" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" href="//lib.baomitu.com/twitter-bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet">
    <link crossorigin="anonymous" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" href="//lib.baomitu.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../lib/shards/shards.min.css">

    <!-- User Defined -->
    <link href="../css/app.min.css" rel="stylesheet">
    <script src="../js/init.min.js"></script>

    <title>星云宝</title>
</head>

<body>
    <div id="app" class="app">
        <!-- app header -->
        <div class="app-header bg-dark">
            <div class="container">
                <!-- Navigation -->
                <nav class="navbar navbar-expand-md navbar-dark px-0">
                    <a href="../" class="navbar-brand"><img src="../images/logo-white.png" width="30" height="30" class="mr-2" alt="" data-i18n="nebpay-name">星云宝</a>

                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-collapse"><span class="navbar-toggler-icon"></span></button>

                    <div id="navbar-collapse" class="collapse navbar-collapse">
                        <ul class="navbar-nav mr-auto">
                            <li class="nav-item">
                                <a class="nav-link" href="../">首页</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="./initial.html">安全交易</a>
                            </li>
                        </ul>
                        <ul class="navbar-nav">
                            <li id="change-chainnet" class="nav-item dropdown d-none">
                                <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown"></a>
                                <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                                    <a class="dropdown-item" href="javascript:" data-chainnet="mainnet">主网</a>
                                    <a class="dropdown-item" href="javascript:" data-chainnet="testnet">测试网</a>
                                </div>
                            </li>
                        </ul>
                    </div>
                </nav>
                <!-- / Navigation -->
            </div>
        </div>

        <!-- app subnav -->
        <div class="app-subnav">
            <div class="container">
                <nav class="nav">
                    <a class="nav-link active" href="./initial.html">发起交易</a>
                    <a class="nav-link" href="./all.html">交易列表</a>
                    <a class="nav-link" href="./handle.html">处理交易</a>
                    <span class="align-items-center px-4 text-light d-none d-md-flex">|</span>
                    <a class="nav-link" href="./help.html">帮助说明 ?</a>
                </nav>
            </div>
        </div>

        <!-- app body -->
        <div class="app-body mt-4">
            <div class="container">
                <div class="row">
                    <div class="col-lg-6 col-md-12">
                        <h4>交易</h4>
                        <div class="form-group">
                            <label>目的地址<i class="fa fa-question-circle ml-2" data-toggle="tooltip" title="收款方的钱包地址!"></i></label>
                            <input name="to" type="text" class="form-control rounded-0" placeholder="">
                        </div>
                        <div class="form-group">
                            <label>交易金额<i class="fa fa-question-circle ml-2" data-toggle="tooltip" title="由于在星云钱包内可更改转账金额，所以交易金额将以实际转账数额为准!"></i></label>
                            <div class="input-group">
                                <input name="txAmount" type="number" class="form-control rounded-0" placeholder="">
                                <div class="input-group-append">
                                    <span class="input-group-text rounded-0">NAS</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>交易周期<i class="fa fa-question-circle ml-2" data-toggle="tooltip" title="如果当前时间超过交易周期，交易账款将默认属于收款方"></i></label>
                            <div class="input-group">
                                <input name="txDuration" type="number" class="form-control rounded-0" placeholder="" value="7">
                                <div class="input-group-append">
                                    <span class="input-group-text rounded-0">天</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 col-md-12 mt-4 mt-lg-0">
                        <h4>纠纷</h4>
                        <div class="form-group">
                            <label>最低纠纷协商保证金<i class="fa fa-question-circle ml-2" data-toggle="tooltip" title="当前产生交易纠纷时，申请协商所需要的最低保证金额；建议设置为交易金额的20%"></i></label>
                            <div class="input-group">
                                <input name="marginAmount" type="number" class="form-control rounded-0" placeholder="">
                                <div class="input-group-append">
                                    <span class="input-group-text rounded-0">NAS</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>纠纷处理周期<i class="fa fa-question-circle ml-2" data-toggle="tooltip" title="如果当前时间超过纠纷处理周期，交易账款及保证金将默认属于纠纷协商申请方"></i></label>
                            <div class="input-group">
                                <input name="disputeDuration" type="number" class="form-control rounded-0" placeholder="" value="3">
                                <div class="input-group-append">
                                    <span class="input-group-text rounded-0">天</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group mt-4">
                    <button id="create" type="button" class="btn btn-dark btn-lg btn-block rounded-0">生成安全交易</button>
                </div>
            </div>

        </div>

        <!-- app footer -->
        <footer class="pt-5 pb-4">
            <div class="container text-center">
                <hr class="mt-0">
                <ul class="nav justify-content-center">
                    <li class="nav-item">
                        <a class="nav-link" href="../">主页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../about.html">关于</a>
                    </li>
                </ul>
                <p class="text-muted m-0">本站基于
                    <a href="https://nebulas.io" target="_blank">Nebulas.io</a> 平台，支持移动端自适应式布局</p>
                <p class="text-muted m-0">Copyright © 2018. Created By KYW & Viggo.Gao. 由
                    <a href="https://gitee.com" target="_blank">Gitee</a> 提供站点托管,
                    <a href="https://cdn.baomitu.com/" target="_blank">Baomitu</a> 提供静态资源CDN
                </p>
            </div>
        </footer>
    </div>

    <!-- Third Party -->
    <script crossorigin="anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" src="//lib.baomitu.com/jquery/3.3.1/jquery.slim.min.js"></script>
    <script crossorigin="anonymous" integrity="sha384-lZmvU/TzxoIQIOD9yQDEpvxp6wEU32Fy0ckUgOH4EIlMOCdR823rg4+3gWRwnX1M" src="//lib.baomitu.com/twitter-bootstrap/4.1.0/js/bootstrap.bundle.min.js"></script>

    <script src="../lib/shards/shards.min.js"></script>
    <script src="../lib/neb/nebulas.min.js"></script>
    <script src="../lib/nebpay/nebPay.min.js"></script>

    <!-- User Defined -->
    <script src="../js/tools.min.js"></script>
    <script src="../js/global.min.js"></script>
    <script>
        // var Nebulas = require('nebulas'),
        //     HttpRequest = Nebulas.HttpRequest,
        //     Neb = Nebulas.Neb,
        //     Account = Nebulas.Account,
        //     Transaction = Nebulas.Transaction,
        //     Unit = Nebulas.Unit,
        //     Utils = Nebulas.Utils;


        // var neb = new Neb();
        // neb.setRequest(new HttpRequest(app.config.host));

        var Nebulas = require('nebulas'),
            Account = Nebulas.Account,
            Unit = Nebulas.Unit,
            Utils = Nebulas.Utils;

        var NebPay = require('nebpay'),
            nebPay = new NebPay();
        var serialNumber; //交易序列号
        var intervalQuery; //定时查询清除器
        var nebPayOptions = {
            qrcode: {
                showQRCode: false
            },
            callback: app.config.payApi, //在测试网查询
            listener: listener
        };

        //查询交易结果. queryPayInfo返回的是一个Promise对象.
        function funcIntervalQuery() {
            nebPay.queryPayInfo(serialNumber, {
                    callback: app.chainnet.payApi
                })
                .then(function(resp) {
                    // console.log("tx result: " + resp)
                    var respObject = JSON.parse(resp)
                    //code==0 交易发送成功, status==1 交易已被打包上链
                    if (respObject.code === 0 && respObject.data.status === 1) {
                        //交易成功,处理后续任务....
                        clearInterval(intervalQuery) //清除定时查询
                        window.location.href = 'handle.html?hash=' + respObject.data.hash;
                    } else if (respObject.data.status === 0) {
                        var errString = respObject.data.execute_error
                        if (errString !== '') {
                            clearInterval(intervalQuery) //清除定时查询
                            swal('失败', '发起交易失败，请检查账户是否有足够余额！', 'error');
                        }
                    }
                })
                .catch(function(err) {
                    console.log(err);
                });
        }

        function listener(resp) {
            // console.log("response of push: " + JSON.stringify(resp))
            var respString = JSON.stringify(resp);
            if (respString.search("rejected by user") !== -1) {
                clearInterval(intervalQuery)
            } else if (respString.search("txhash") !== -1) {
                console.log("wait for tx result: " + resp.txhash)
            }
        }

        $(document).ready(function($) {
            'use strict';

            $('[data-toggle="tooltip"]').tooltip();

            //to check if the extension is installed
            //if the extension is installed, var "webExtensionWallet" will be injected in to web page
            if (typeof(webExtensionWallet) === "undefined" && !isMobile()) {
                $('.app-body .container').prepend('<div class="alert alert-warning"><i class="fa fa-warning"></i> <strong>Oops!</strong> 您尚未在浏览器中安装<a href="https://github.com/ChengOrangeJu/WebExtensionWallet"><strong>【星云官方钱包插件】</strong></a>，无法正常使用安全交易功能！</div>');
                return;
            }

            function formCreate() {
                var to = $.trim($('input[name="to"]').val());
                var txAmount = Utils.toBigNumber(parseFloat($('input[name="txAmount"]').val()));
                var txDuration = Utils.toBigNumber($('input[name="txDuration"]').val());
                var marginAmount = Utils.toBigNumber($('input[name="marginAmount"]').val());
                var disputeDuration = Utils.toBigNumber($('input[name="disputeDuration"]').val());

                if (!Account.isValidAddress(to)) {
                    swal('错误', '目的地址不是有效的钱包地址，请重新输入！', 'error').then(function() {
                        $('input[name="to"]').focus();
                    });
                    return;
                }

                if (txAmount.isNaN() || txAmount.lte(0.000001)) {
                    swal('提示', '交易金额必须 大于 0.000001 Nas！', 'warning').then(function() {
                        $('input[name="txAmount"]').focus();
                    });
                    return;
                }

                if (txDuration.isNaN() || !txDuration.isInteger() || txDuration.lt(1)) {
                    swal('提示', '交易周期必须是 大于等于 1 的正整数', 'warning').then(function() {
                        $('input[name="txDuration"]').focus();
                    });
                    return;
                }

                if (marginAmount.isNaN() || marginAmount.lte(0.000001)) {
                    swal('提示', '最低纠纷协商保证金必须 大于 0.000001 Nas！', 'warning').then(function() {
                        $('input[name="marginAmount"]').focus();
                    });
                    return;
                }
                marginAmount = Unit.toBasic(marginAmount, 'nas');

                if (disputeDuration.isNaN() || !disputeDuration.isInteger() || disputeDuration.lt(1)) {
                    swal('提示', '纠纷处理周期必须是 大于等于 1 的正整数', 'warning').then(function() {
                        $('input[name="disputeDuration"]').focus();
                    });
                    return;
                }

                swal({
                    title: "确认发起安全交易吗？",
                    text: "该操作将会调用【星云钱包】并将账款转至智能合约账户内，如果在星云钱包内更改了转账金额，则实际交易金额以转账金额为准！",
                    icon: "warning",
                    buttons: true,
                    dangerMode: true,
                }).then(function(wannaDo) {
                    if (!wannaDo) {
                        return;
                    }

                    var callArgs = JSON.stringify([to, txDuration, marginAmount, disputeDuration]);

                    //发送交易(发起智能合约调用)
                    serialNumber = nebPay.call(app.config.dappAddress, txAmount, 'fromCreate', callArgs, nebPayOptions);

                    //设置定时查询交易结果
                    intervalQuery = setInterval(function() {
                        funcIntervalQuery();
                    }, 15000); //建议查询频率10-15s,因为星云链出块时间为15s,并且查询服务器限制每分钟最多查询10次。
                });
            }

            $('#create').click(formCreate);
        });
    </script>
</body>

</html>
